package com.chatplus.application.config.ws.interceptor;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.http.HtmlUtil;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.web.satoken.helper.LoginHelper;
import com.chatplus.application.web.satoken.model.LoginUser;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket握手请求的拦截器
 */
@Component
public class PlusWebSocketInterceptor implements HandshakeInterceptor {

    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(PlusWebSocketInterceptor.class);

    /**
     * 握手前
     *
     * @param request    domain
     * @param response   response
     * @param wsHandler  wsHandler
     * @param attributes attributes
     * @return 是否握手成功
     */
    @Override
    public boolean beforeHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Map<String, Object> attributes) {
        // 提取 GET 参数
        String url = HtmlUtil.unescape(request.getURI().toString());
        UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).build();
        MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
        String token = queryParams.get("token").getFirst();
        attributes.put("session_id", queryParams.get("session_id").getFirst());
        attributes.put("chat_id", queryParams.get("chat_id").getFirst());
        attributes.put("role_id", queryParams.get("role_id").getFirst());
        attributes.put("model_id", queryParams.get("model_id").getFirst());
        attributes.put("token", token);
        LoginUser loginUser = LoginHelper.getLoginUser(token);
        if (loginUser == null) {
            LOGGER.message("WebSocket认证失败,无法访问系统资源").warn();
            StpUtil.logoutByTokenValue(token);
            return false;
        }
        attributes.put("userId", loginUser.getUserId());
        return true;
    }

    /**
     * 握手后
     *
     * @param request   domain
     * @param response  response
     * @param wsHandler wsHandler
     * @param exception 异常
     */
    @Override
    public void afterHandshake(@NotNull ServerHttpRequest request, @NotNull ServerHttpResponse response, @NotNull WebSocketHandler wsHandler, Exception exception) {

    }
}
